package cloud.code.baseProject.util;

import cloud.code.baseProject.exception.RedisBusinessException;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Created by zhanghaichao on 2019/12/18.
 */
public class RedisUtil {

    /**
     * 通过key获取储存在redis中的value
     * 并释放连接
     *
     * @param key
     * @param indexdb 选择redis库 0-15
     * @return 成功返回value 失败返回null
     */
    public static String get(JedisPool jedisPool, String key, int indexdb) {
        Jedis jedis = null;
        String value = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(indexdb);
            value = jedis.get(key);
        } catch (Exception e) {
            throw new RedisBusinessException(e);
        } finally {
            returnResource(jedis);
        }
        return value;
    }

    /**
     * 向redis存入key和value,并释放连接资源
     * 如果key已经存在 则覆盖
     *
     * @param key
     * @param value
     * @param indexdb 选择redis库 0-15
     * @return 成功 返回OK 失败返回 0
     */
    public static String set(JedisPool jedisPool, String key, String value, int indexdb) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(indexdb);
            return jedis.set(key, value);
        } catch (Exception e) {
            throw new RedisBusinessException(e);
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 返还到连接池
     *
     * @param jedis
     */
    private static void returnResource(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }
}
